<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>动力节点聊天</title>
    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.min.js"></script>
    <script src="http://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
    <script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
</head>

<body style="margin: 45px;">
<h4>动力在线聊天室</h4>
<div class="form-group">
    <label for="content"></label>
    <textarea id="content" readonly="readonly" cols="80" rows="15"></textarea>
</div>
<div class="form-group" style="margin-top: 8px">
    <textarea id="message" cols="80" rows="5" placeholder="请输入消息"></textarea>
    <div style="margin-top: 10px">
        <button id="toSend" class="btn btn-info">发送</button>
        <button id="user_exit" class="btn btn-danger">离开</button>
        <input id="username" th:value="${username}" name="username" style="display: none">
    </div>
</div>

<script type="text/javascript">
    $(function () {
        var ws;
        if ("WebSocket" in window) {
            var baseUrl = 'ws://localhost:8011/websocket/';
            var userName = $('#username').val();
            debugger
            ws = new WebSocket(baseUrl + userName);

            // 连通之后的回调事件，建立连接
            ws.onopen = function () {
                console.log("建立 websocket 连接...");
            };

            // 接收后台服务端的消息
            ws.onmessage = function (event) {
                $('#content').append(event.data + '\n\n');
                console.log("接收到服务端发送的消息..." + event.data + '\n');
            };

            ws.onerror = function (event) {
                console.log("websocket发生错误..." + event + '\n');
            }

            // 连接关闭的回调事件
            ws.onclose = function () {
                $('#content').append('[' + userName + '] 已离开!');
                console.log("关闭 websocket 连接...");
            };
        } else {
            // 浏览器不支持 WebSocket
            alert("您的浏览器不支持WebSocket!");
        }

        // 客户端发送消息到服务器
        $('#toSend').click(function () {
            sendMsg();
        });

        $(document).keyup(function (event) {
            // 回车键事件
            if (event.keyCode == 13) {
                sendMsg();
            }
        });

        // 发送消息
        function sendMsg() {
            //websocket发送消息
            ws.send($('#message').val());
            $('#message').val("");
        }

        // 退出
        $('#user_exit').click(function () {
            if (ws) {
                ws.close();
            }
        });
    });
</script>
</body>
</html>